package com.example.administrator.myview.voice;

import android.media.MediaPlayer;
import android.util.Log;


/**
 * 播放录音用的 可以回去找找以前的音乐播放器demo 利用service
 * Created by Administrator on 2017/11/14.
 */

public class MediaManager {
    private static MediaPlayer mMediaPlayer;
    private static boolean isPause;

    /**
     * 播放音乐
     * @param filePath//文件路径
     * @param onCompletionListener//播放完成监听
     */
    public static void playSound(String filePath,MediaPlayer.OnCompletionListener onCompletionListener) {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
            //设置一个error监听器
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

                public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
                    mMediaPlayer.reset();
                    return false;
                }
            });
        } else {
            mMediaPlayer.reset();
        }
        try {
            mMediaPlayer.reset();
            mMediaPlayer.setAudioStreamType(android.media.AudioManager.STREAM_MUSIC);//必须用系统提供的 播放类型音乐
            mMediaPlayer.setOnCompletionListener(onCompletionListener);
            mMediaPlayer.setDataSource(filePath);
            mMediaPlayer.prepare();//预加载音频
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("错误",e.toString());//prepare fail status=0x1
        }
        mMediaPlayer.start();
    }


    /**
     * 暂停播放
     */
    public static void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { //正在播放的时候
            mMediaPlayer.pause();
            isPause = true;
        }
    }

    /**
     * 当前是isPause状态
     */
    public static void resume() {
        if (mMediaPlayer != null && isPause) {
            mMediaPlayer.start();
            isPause = false;
        }
    }

    /**
     * 释放资源
     */
    public static void release() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}
